package com.itouch.bracelet.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.itouch.bracelet.R;
import com.itouch.bracelet.adapter.NewFriendsAdapter;
import com.itouch.bracelet.adapter.NewFriendsAdapter.AddLinstener;
import com.itouch.bracelet.bean.BaseResult;
import com.itouch.bracelet.bean.LoginResult;
import com.itouch.bracelet.bean.NewFriend;
import com.itouch.bracelet.bean.NewFriendsResult;
import com.itouch.bracelet.cache.UserCache;
import com.itouch.bracelet.diseaseinfo.Constants;
import com.itouch.util.JsonAndPhpUtil;
import com.itouch.util.StringUtils;
import com.itouch.widget.ActionSheet;
import com.itouch.widget.ActionSheet.ActionSheetListener;

/**
 * cocoaSJ
 */
public class NewFriendsActivity extends BaseActivity implements 
		OnItemClickListener ,AddLinstener,ActionSheetListener{

	private static final String LOG_TAG = "NewFriendsActivity";
	private ListView listview;
	private ArrayList<NewFriend> list;
	private NewFriendsAdapter adapter;
	private int chickPosition;
	
	@Override
	protected int setContentViewById() {
		return R.layout.activity_newfriends;
	}

	@Override
	protected void initViews() {
		listview = (ListView) findViewById(
				R.id.listview);
		list = new ArrayList<NewFriend>();
		adapter = new NewFriendsAdapter(this, list);
		adapter.setListener(this);
		listview.setAdapter(adapter);
		listview.setOnItemClickListener(this);
		getFriends();
	}

	@Override
	protected void initData() {
	
	}
	
	
	
	private void getFriends() {
		show();
		
		if(list !=null){
			list.clear();
		}
		if(adapter!=null){
			adapter.notifyDataSetChanged();
		}
		
		Uri.Builder builder = Uri.parse(Constants.GET_FRIEND)
				.buildUpon();
		builder.appendQueryParameter("id", UserCache.getOauth(context).getUserId());
		Log.d("GET_NEARBY",
				"GET_NEARBY==POST" + builder.toString());
		getJSONByVolleyGET(builder.toString(), 
				new Response.Listener<JSONObject>() {

					@Override
					public void onResponse(JSONObject arg0) {
						disMiss();
						Log.d("GET_NEARBY",
								"GET_NEARBY" + arg0.toString());
						try {
							NewFriendsResult a = new Gson().fromJson(
									arg0.toString(), NewFriendsResult.class);
							if (a == null) {
								return;
							}
							if (a.isFlag()) {
								List<NewFriend> apiList = a.getRows();
								if(apiList!=null&apiList.size()>0){
									list.addAll(apiList);
									adapter.notifyDataSetChanged();
								}
							} else {
								Toast.makeText(context,
										a.getMsg() + "",
										Toast.LENGTH_LONG).show();
							}
						} catch (Exception e) {
						}
					}

				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError arg0) {
						disMiss();
						Toast.makeText(context,
								getString(R.string.net_error) + "",
								Toast.LENGTH_LONG).show();
					}
				});

	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

	}

	public void add(int position) {
		try{
			chickPosition=position;
			setTheme(R.style.ActionSheetStyleIOS7);
			ActionSheet
					.createBuilder(this,
							getSupportFragmentManager())
					.setCancelButtonTitle("取消")
					.setOtherButtonTitles("同意", "拒绝")
					.setCancelableOnTouchOutside(true)
					.setListener(this).show();
		}catch(Exception x){
			
		}
		
	}
	
	
	class AddFriendAsync extends AsyncTask<String, String, String> {

		public String id;
		public String isagree;
		public AddFriendAsync(String id, String isagree) {
			super();
			this.id = id;
			this.isagree = isagree;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			show();
		}

		@Override
		protected String doInBackground(String... params) {
			List<NameValuePair> lists = new ArrayList<NameValuePair>();
			
			lists.add(new BasicNameValuePair("id", id));
			lists.add(new BasicNameValuePair("isagree", isagree));
			String ss = JsonAndPhpUtil.postHttpData(Constants.AGREE_FRIEND,
					lists, context);
			Log.i("AGREE_FRIEND", "AGREE_FRIEND" + ss);
			return ss;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			disMiss();
			Log.e("AGREE_FRIEND", "AGREE_FRIEND" + result);
			if (!StringUtils.isNull(result)) {
				BaseResult a = new Gson().fromJson(result, LoginResult.class);
				if (a != null && a.isFlag()) {
					getFriends();
				} else {
					String message = a.getMsg();
					Toast.makeText(context, message + "", Toast.LENGTH_LONG)
							.show();
				}
			} else {
				// 网络失败
				Toast.makeText(context, "请求失败，请稍后再试..", Toast.LENGTH_LONG)
						.show();
			}
		}
	}
	
	
	
	
//	192.168.3.222:83/handchain/rong/relation/agreeapplication?id=85&isagree=1
//	isagree(1：同意添加好友；2：不同意添加好友)
	private void addFriend(String id,String isagree) {
		show();
		Uri.Builder builder = Uri.parse(Constants.AGREE_FRIEND)
				.buildUpon();
		builder.appendQueryParameter("id", id);
		builder.appendQueryParameter("isagree", isagree);
		Log.d("AGREE_FRIEND",
				"AGREE_FRIEND" + builder.toString());
		getJSONByVolleyGET(builder.toString(), 
				new Response.Listener<JSONObject>() {

					@Override
					public void onResponse(JSONObject arg0) {
						disMiss();
						Log.d("AGREE_FRIEND",
								"AGREE_FRIEND" + arg0.toString());
						try {
							BaseResult a = new Gson().fromJson(
									arg0.toString(), BaseResult.class);
							if (a == null) {
								return;
							}
							if (a.isFlag()) {
								getFriends();
							
							} else {
								Toast.makeText(context,
										a.getMsg() + "",
										Toast.LENGTH_LONG).show();
							}
						} catch (Exception e) {
						}
					}

				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError arg0) {
						disMiss();
						Toast.makeText(context,
								getString(R.string.net_error) + "",
								Toast.LENGTH_LONG).show();
					}
				});

	}

	@Override
	public void onDismiss(ActionSheet actionSheet, boolean isCancel) {
		
		
	}

	@Override
	public void onOtherButtonClick(ActionSheet actionSheet, int index) {
		if(chickPosition<0){
			return;
		}
		String isAgree = index==0 ? "1":"2";
		NewFriend temp = list.get(chickPosition);
		new AddFriendAsync(temp.getId(),isAgree).execute();
	}

	
	
}